package cn.alm.template_backend_project.service.impl;

import cn.alm.template_backend_project.common.CommonResponse;
import cn.alm.template_backend_project.entity.LoginForm;
import cn.alm.template_backend_project.entity.User;
import cn.alm.template_backend_project.mapper.UserMapper;
import cn.alm.template_backend_project.service.AuthService;
import cn.alm.template_backend_project.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public CommonResponse login(LoginForm loginForm) {
        // 验证用户名和密码
        User user = userMapper.findByUsernameAndPassword(loginForm.getUsername(), loginForm.getPassword());
        
        if (user == null) {
            return new CommonResponse(400, "用户名或密码错误", null);
        }

        // 检查用户状态
        if (user.getStatus() != 1) {
            return new CommonResponse(400, "用户已被停用", null);
        }

        // 生成JWT token
        String token = jwtUtil.generateToken(user.getUsername());

        // 将token存入Redis，设置过期时间为1小时
        String redisKey = "token:" + token;
        redisTemplate.opsForValue().set(redisKey, user.getUsername(), 1, TimeUnit.HOURS);

        // 返回token
        Map<String, String> data = new HashMap<>();
        data.put("token", token);

        return new CommonResponse(200, "登录成功", data);
    }

    @Override
    public CommonResponse logout(String token) {
        if (token == null || token.isEmpty()) {
            return new CommonResponse(400, "token不能为空", null);
        }

        // 从Redis中删除token
        String redisKey = "token:" + token;
        redisTemplate.delete(redisKey);

        return new CommonResponse(200, "退出成功", null);
    }
}